﻿using Ljy_VoteSys.Models.Database;
using Ljy_VoteSys.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Json;
using System.Threading.Tasks;

namespace Ljy_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CompanydetailssController : Controller
    {
        //定义数据库上下文
        private readonly Ljy_VoteSysContext _db;
        //注入jwt服务
        private readonly IJWTService _jwtService;
        //jwt用户
        public string User => Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value;

        public CompanydetailssController(IJWTService jwtService, Ljy_VoteSysContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }
        /// <summary>
        /// 根据投票id查询企业
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<CompanyDetail> FindItem(int ItemId)
        {
            //var CompanyName = "";
            var data = _db.Tickets.FirstOrDefault( x=>x.Itemid ==ItemId);
            if (data != null)
            {
                
                var detail = _db.CompanyDetails.Where(x => x.CompanyName == data.CompanyName).ToList();

                if (detail != null)
                {

                    return detail;
                }
                else  return null; 
            }
            else  return null; 
          
           
        }
        /// <summary>
        /// 登录情况下输入项目id,每日最多5.........
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [Authorize]
        public string GetTicket(int ItemId)
        {
            var check = _db.UserTables.FirstOrDefault(x => x.Username == User);
            if (check==null)
                return " 您不是普通用户,请重新登录";
            var data = _db.Tickets.FirstOrDefault(x => x.Itemid == ItemId);
            if (data == null)
                return "找不到此作品,请重新输入";
            if (check.TicketOneday > 0) { 
             data.TotalTicket = data.TotalTicket + 1;
            check.TicketOneday = check.TicketOneday - 1;
                var row = _db.SaveChanges();
                if (row > 0)
                    return "用户投票成功,你当前还可以投"+check.TicketOneday+"票";
            }
            return "您今日投票次数已用完,请明天再投票";
            
        }

        //
    }
}
